package com.starpl.mobile.android.monthunsae.november.activity;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.starpl.mobile.android.monthunsae.november.R;
import com.starpl.mobile.android.monthunsae.november.command.MonthUnsaeCommand;
import com.starpl.mobile.android.monthunsae.november.common.LoginUtil;
import com.starpl.mobile.android.monthunsae.november.component.MenuButtonLayout;
import com.starpl.mobile.android.monthunsae.november.domain.Keyword;
import com.starpl.mobile.android.monthunsae.november.domain.MenuButton;
import com.starpl.mobile.android.monthunsae.november.domain.MonthUnsae;
import com.starpl.mobile.android.monthunsae.november.domain.UserInfo;
import com.starpl.mobile.android.platform.common.KeywordUtil;
import com.starpl.mobile.android.platform.common.ads.AdBannerOnClickListener;
import com.starpl.mobile.android.platform.common.base.BaseActivity;
import com.starpl.mobile.android.platform.common.base.BaseApplication;
import com.starpl.mobile.android.platform.common.network.HttpHandler;


/**
 * 홈 Activity
 * 
 * @author 우연화
 * @since 2011.03.16
 */
public class HomeActivity extends BaseActivity implements OnClickListener
{
	private final int HOME_MENU_MONTH_UNSAE = 1;
	private final int HOME_MENU_DAILY_UNSAE = 10000097;
	private final int HOME_MENU_LOVE_UNSAE 	= 10084402;
	private final int HOME_MENU_MONEY_UNSAE = 10001374;
	private final int HOME_MENU_TOTAL_UNSAE = 3;
	private final int HOME_MENU_SIMSIM_FREE = 4;
	private final int HOME_MENU_ADD_COMMUNITY = 2;
	private final int HOME_MENU_STARPL = 17;

	private static final int OPTION_MENU_ADD_COMMUNITY = 0;
	private static final int OPTION_MENU_REFRESH = 1;
	private static final int OPTION_MENU_LOGOUT = 2;

	private String mUrl;
	private String mRedirectUrlForTotal;
	private String mHomeMenuNameForTotal;
	private String mDefaultName;

	private ImageButton mIbRefresh;
	private ImageButton mIbSetting;

	private LinearLayout mLlHomeMenu;

	private TextView mTvQuickProfile;
	private TextView mTvQuickReply;
	private TextView mTvQuickMessage;
	private TextView mTvQuickEvent;

	private ImageView mIvNewReply;
	private ImageView mIvNewMessage;
	private ImageView mIvNewEvent;

	private ArrayList<Keyword> mKeywordList;
	private ArrayList<MenuButton> mButtonList;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.starpl.platform.common.base.BaseActivity#onCreate(android.os.Bundle)
	 */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home_activity);

		// 새로고침 & 설정
		mIbRefresh = (ImageButton) findViewById(R.id.home_activity_ib_refresh);
		mIbSetting = (ImageButton) findViewById(R.id.home_activity_ib_setting);

		mIbRefresh.setOnClickListener(this);
		mIbSetting.setOnClickListener(this);

		// 대쉬보드
		mLlHomeMenu = (LinearLayout) findViewById(R.id.home_activity_ll_homemenu);

		// 퀵 메뉴
		mTvQuickProfile = (TextView) findViewById(R.id.home_activity_tv_quick_profile);
		mTvQuickReply = (TextView) findViewById(R.id.home_activity_tv_quick_reply);
		mTvQuickMessage = (TextView) findViewById(R.id.home_activity_tv_quick_message);
		mTvQuickEvent = (TextView) findViewById(R.id.home_activity_tv_quick_event);

		mTvQuickProfile.setOnClickListener(this);
		mTvQuickReply.setOnClickListener(this);
		mTvQuickMessage.setOnClickListener(this);
		mTvQuickEvent.setOnClickListener(this);

		// 퀵 메뉴 NEW 버튼
		mIvNewReply = (ImageView) findViewById(R.id.home_activity_iv_quick_reply);
		mIvNewMessage = (ImageView) findViewById(R.id.home_activity_iv_quick_message);
		mIvNewEvent = (ImageView) findViewById(R.id.home_activity_iv_quick_event);

		mKeywordList = new ArrayList<Keyword>();
		mButtonList = new ArrayList<MenuButton>();
		
		mDefaultName = BaseApplication.getConfigPersistent("defaultName");
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.starpl.platform.common.base.BaseActivity#onResume()
	 */
	@Override
	protected void onResume()
	{
		super.onResume();

		setMenu();
	}

	/**
	 * 서버에서 데이터를 가져와 메뉴를 세팅한다.
	 */
	private void setMenu()
	{
		MonthUnsaeCommand.getMainAlarm(new HttpHandler(this)
		{
			@Override
			public void didSucceed(Object result)
			{
				try
				{
					JSONObject userData = (JSONObject) result;
					
					JSONObject data = userData.getJSONObject("data");
					
					JSONArray extraData1 = userData.getJSONArray("extData1");

					mRedirectUrlForTotal = null;
					mHomeMenuNameForTotal = null;
					if(!userData.isNull("extData3"))
					{
						JSONObject extData3 = userData.getJSONObject("extData3");
						
						mRedirectUrlForTotal = extData3.isNull("sinbiunUrl") ? null : extData3.getString("sinbiunUrl");
						mHomeMenuNameForTotal = extData3.isNull("sinbiunName") ? "종합운세" : extData3.getString("sinbiunName");
					}
					
					getKeywrodList(extraData1);
					setQuickMenu(data, mIvNewReply, mIvNewMessage, mIvNewEvent);

					if(!userData.isNull("extData2"))
					{
						JSONObject extData2 = userData.getJSONObject("extData2"); 
						
						mUrl = extData2.isNull("marketUrl") ? null : extData2.getString("marketUrl");
						mButtonList.add(new MenuButton(R.drawable.btn_quickmenu_app, "스타플어플", HOME_MENU_STARPL));
					}
					
					// 대쉬보드에 메뉴버튼을 세팅한다.
					setHomeMenu();

					// 홈 데이터를 받아온 후 월별운세 데이터를 받아온다.
					getMonthUnsae();
				}
				catch(JSONException e)
				{
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * 운세정보를 가져와서 전역변수에 저장한다.
	 */
	private void getMonthUnsae()
	{
		// 운세정보를 이미 가져온 경우에는 다시 가져오지 않는다.

		MonthUnsae monthUnsae = (MonthUnsae) BaseApplication.getGlobalPersistent("monthUnsae");

		if(monthUnsae == null)
		{
			MonthUnsaeCommand.getMonthUnsae(new HttpHandler(this, "운세 정보를 가져오는중 입니다")
			{
				@Override
				public void didSucceed(Object result)
				{
					MonthUnsae monthUnsae = new MonthUnsae((JSONObject) result);

					BaseApplication.setGlobalPersistent("monthUnsae", monthUnsae);
				}
			});
		}
	}

	/**
	 * 키워드를 가져와 홈메뉴 버튼을 만든다.
	 */
	private void getKeywrodList(JSONArray array)
	{
		int length = array.length();
		
		MenuButton menuButton;

		mKeywordList.clear();
		mButtonList.clear();

		// 월별운세 메뉴 추가
		menuButton = new MenuButton(R.drawable.btn_quickmenu_01, mDefaultName, HOME_MENU_MONTH_UNSAE);
		mButtonList.add(menuButton);

		// 오늘의운세 메뉴 추가
		menuButton = new MenuButton(R.drawable.btn_quickmenu_02, "오늘의운세", HOME_MENU_DAILY_UNSAE);
		mButtonList.add(menuButton);

		// 연애운캘린더 추가
		menuButton = new MenuButton(R.drawable.btn_quickmenu_03, "연애운캘린더", HOME_MENU_LOVE_UNSAE);
		mButtonList.add(menuButton);
		
		// 재물운캘린더추가
		menuButton = new MenuButton(R.drawable.btn_quickmenu_04, "재물운캘린더", HOME_MENU_MONEY_UNSAE);
		mButtonList.add(menuButton);
		
		// 종합운세 추가
		if(mRedirectUrlForTotal != null)
		{
			menuButton = new MenuButton(R.drawable.btn_quickmenu_05, mHomeMenuNameForTotal, HOME_MENU_TOTAL_UNSAE);
			mButtonList.add(menuButton);
		}
		
		// 심심Free 만화
//		menuButton = new MenuButton(R.drawable.btn_quickmenu_partner, "무료만화", HOME_MENU_SIMSIM_FREE);
//		menuButton.setTag(5);
//		mButtonList.add(menuButton);
		
		// USAGE: 전역 키워드관리 유틸 생성
		KeywordUtil keywordUtil = KeywordUtil.getInstance();
		keywordUtil.putKeyword(HOME_MENU_DAILY_UNSAE, "일상");
		keywordUtil.putKeyword(HOME_MENU_LOVE_UNSAE, "연애");
		keywordUtil.putKeyword(HOME_MENU_MONEY_UNSAE, "재테크");
		
		for(int i = 0 ; i < length ; i++)
		{
			try
			{
				// 키워드를 만든다.
				Keyword keyword = new Keyword(array.getJSONObject(i));

				if(keyword.isUseFlag())
				{
					menuButton = new MenuButton(R.drawable.btn_quickmenu_community, keyword.getKeywordName(),
							keyword.getKeywordIdx());
					mButtonList.add(menuButton);
				}

				// 만들어진 키워드를 키워드리스트에 추가한다.
				mKeywordList.add(keyword);
				
				// USAGE: 전역변수에 키워드를 추가한다.
				keywordUtil.putKeyword(keyword.getKeywordIdx(), keyword.getKeywordName());
			}
			catch(JSONException e)
			{
				e.printStackTrace();
			}
		}

		// 커뮤니티추가 메뉴 추가
		menuButton = new MenuButton(R.drawable.btn_quickmenu_addcomm, "커뮤니티추가", HOME_MENU_ADD_COMMUNITY);
		mButtonList.add(menuButton);
	}

	/**
	 * 버튼들을 대쉬보드에 세팅(추가)한다.
	 */
	private void setHomeMenu()
	{
		// 유저정보 객체를 받아와서 키워드 데이터를 추가한다.
		BaseApplication.setGlobalPersistent("keywordList", mKeywordList);

		// 기존 홈/메뉴를 구성한 버튼을 지운다.
		mLlHomeMenu.removeAllViewsInLayout();

		int buttonWidth = 120;
		int rowWidth = 440;
		int buttonCountInRow = rowWidth / buttonWidth;

		int index = 1;
		LinearLayout layoutRow = null;
		for(MenuButton menuButton : mButtonList)
		{
			if(index % buttonCountInRow == 1)
			{
				layoutRow = new LinearLayout(this);
				layoutRow.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
				layoutRow.setOrientation(LinearLayout.HORIZONTAL);
				mLlHomeMenu.addView(layoutRow);
			}

			MenuButtonLayout newButton = new MenuButtonLayout(this);
			newButton.setOnClickListener(this);

			newButton.setButton(menuButton.getButtonResource(), menuButton.getButtonText(), menuButton.getButtonCode());

			newButton.setTag((index - 1));

			layoutRow.addView(newButton);
			index++;
		}
	}

	/**
	 * 홈/메뉴 액티비티 하단 퀵 메뉴 버튼을 갱신합니다.
	 * 
	 * @param data
	 *            JSONObject
	 * @param reply
	 *            퀵 메뉴 댓글 NEW 버튼
	 * @param message
	 *            퀵 메뉴 쪽지 NEW 버튼
	 * @param event
	 *            퀵 메뉴 이벤트 NEW 버튼
	 */
	private void setQuickMenu(JSONObject data, ImageView reply, ImageView message, ImageView event)
	{
		// 홈/메뉴 액티비티 하단 퀵 메뉴 버튼을 세팅한다.
		try
		{
			setNewImage(reply, data.getInt("newCommentCount"));
			setNewImage(message, data.getInt("newMessageCount"));
			setNewImage(event, data.getInt("newEventCount"));
		}
		catch(JSONException e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * 새 내용이 있는지를 확인하고 이미지 뷰(NEW이미지)의 VISIBLE을 세팅한다.
	 * 
	 * @param iv
	 *            이미지뷰
	 * @param newCount
	 *            새 내용 카운트
	 */
	private void setNewImage(ImageView iv, int newCount)
	{
		if(newCount > 0)
		{
			iv.setVisibility(ImageView.VISIBLE);
		}
		else
		{
			iv.setVisibility(ImageView.INVISIBLE);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v)
	{
		Bundle extras;
		String userId;
		String nickname;
		int userIdx;

		switch(v.getId())
		{
		// 새로고침
		case R.id.home_activity_ib_refresh:
			setMenu();
			return;
			// 설정
		case R.id.home_activity_ib_setting:
			getNewActivity().setTargetActivity(SettingActivity.class).show();
			return;

			// //////////////////
			// 퀵 메뉴 버튼

			// 프로필
		case R.id.home_activity_tv_quick_profile:

			extras = new Bundle();
			UserInfo userInfo = (UserInfo) BaseApplication.getGlobalPersistent("userInfo");
			userId = userInfo.getUserId();
			nickname = userInfo.getNickName();
			userIdx = userInfo.getUserIdx();

			extras.putString("userId", userId);
			extras.putInt("userIdx", userIdx);
			extras.putString("nickname", nickname);

			getNewActivity().setBundle(extras).setTargetActivity(ProfileActivity.class).show();

			return;

			// 댓글
		case R.id.home_activity_tv_quick_reply:

			getNewActivity().setTargetActivity(CommentActivity.class).show();

			return;

			// 쪽지
		case R.id.home_activity_tv_quick_message:

			extras = new Bundle();
			userId = ((UserInfo) BaseApplication.getGlobalPersistent("userInfo")).getUserId();
			nickname = ((UserInfo) BaseApplication.getGlobalPersistent("userInfo")).getNickName();
			userIdx = ((UserInfo) BaseApplication.getGlobalPersistent("userInfo")).getUserIdx();
			extras.putString("userId", userId);
			extras.putString("nickname", nickname);
			extras.putInt("userIdx", userIdx);

			getNewActivity().setBundle(extras).setTargetActivity(MessageActivity.class).show();

			return;

			// 이벤트
		case R.id.home_activity_tv_quick_event:

			extras = new Bundle();
			extras.putString("title", "이벤트");
			extras.putString("url", BaseApplication.getConfigPersistent("eventUrl"));

			getNewActivity().setBundle(extras).setTargetActivity(WebViewActivity.class).show();

			return;
		}

		// //////////////////
		// 메뉴(대쉬보드) 버튼

		int position = (Integer) v.getTag();
		MenuButton button = mButtonList.get(position);
		int keywordIdx = button.getButtonCode();

		switch(keywordIdx)
		{

		// 일상 커뮤니티 호출
		case HOME_MENU_MONTH_UNSAE:
			 getNewActivity()
			 .setTargetActivity(UnsaeActivity.class)
			 .show();
			return;

		// 오늘의운세
		case HOME_MENU_DAILY_UNSAE:
			getNewActivity()
			.setTargetActivity(UnsaeDailyActivity.class)
			.show();
			return;

		// 종합운세
		case HOME_MENU_TOTAL_UNSAE:
			if(mRedirectUrlForTotal == null)
			{
				return;
			}
			startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(mRedirectUrlForTotal)));
			break;
			
		// 심심프리 모듈
		case HOME_MENU_SIMSIM_FREE:
//			Intent i = new Intent(this , Starter.class);
//			i.putExtra("CPAPPID", BaseApplication.getConfigPersistent("eslpAppId"));
//			i.putExtra("APPNAME", BaseApplication.getConfigPersistent("defaultName"));
//			i.putExtra("ADULT", false);
//			startActivity(i);
			return;
			
		// 커뮤니티 추가 액티비티 호출
		case HOME_MENU_ADD_COMMUNITY:
			 getNewActivity()
			 .setTargetActivity(AddCommunityActivity.class)
			 .show();
			return;

		// 스타플 어플 아이콘 클릭
		case HOME_MENU_STARPL:
			AdBannerOnClickListener adBanner = new AdBannerOnClickListener(mUrl);
			adBanner.goMarketOrTstore();
			return;

			// 커뮤니티 호출
		default:
			extras = new Bundle();
			extras.putInt("keywordIdx", keywordIdx);

			 getNewActivity()
			 .setTargetActivity(CommunityActivity.class)
			 .setBundle(extras)
			 .show();

			return;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.starpl.platform.common.base.BaseActivity#onCreateOptionsMenu(android
	 * .view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		menu.addSubMenu(0, OPTION_MENU_ADD_COMMUNITY, 0, "커뮤니티추가").setIcon(R.drawable.icon_menu_add);
		menu.addSubMenu(0, OPTION_MENU_REFRESH, 0, "새로고침").setIcon(R.drawable.icon_menu_refresh);
		menu.addSubMenu(0, OPTION_MENU_LOGOUT, 0, "로그아웃").setIcon(R.drawable.icon_menu_logout);
		return true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.starpl.platform.common.base.BaseActivity#onOptionsItemSelected(android
	 * .view.MenuItem)
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch(item.getItemId())
		{
		case OPTION_MENU_ADD_COMMUNITY:
			 getNewActivity()
			 .setTargetActivity(AddCommunityActivity.class)
			 .setRemoveToActivity(HomeActivity.class)
			 .show();
			break;

		case OPTION_MENU_REFRESH:
			mButtonList.clear();
			setMenu();
			break;
		case OPTION_MENU_LOGOUT:
			LoginUtil.logoutUser(this);
			break;
		}
		return false;
	}
}
